<template>
  <div style="width:90%;margin:10px auto 0">
    <!-- pdf -->
    <!-- <iframe :src="pdfUrl" width="100%" height="775px" v-if="pdfShow"></iframe>  -->
    <!-- <shukeOfd v-if="pdfShow" :infoItem="infoItem"></shukeOfd> -->
    <!--1.pdf 2.ofd 3.word 4.xls 5.mp4 6.mp3  7.jpg png  -->
    <div style="width:100%;margin:0 auto" v-if="itemList.DOC_FILE_TYPE == 'PDF'">
      <pdfDemo :url="pdfUrl" :istype="istype" :source="source" v-if="isUrl && pdfUrl"></pdfDemo>
      <div style="position: relative;overflow: hidden;background:#dfe6ec;widht:100%"
        :style="istype == '1' ? 'height:740px' : 'height: 790px'" v-else>
        <imgViever v-if="imgList.length > 0" :imgList="imgList" :listLength="imgList.length"
          style="z-index: 99999999999999;"></imgViever>
        <previewPicture v-if="pdfUrl" :imgUrl="pdfUrl"></previewPicture>
      </div>
    </div>
    <!-- txt -->
    <iframe :src="txtUrl" width="100%" height="775px" v-if="itemList.DOC_FILE_TYPE == 'TXT'"></iframe>
    <!-- <div  v-if="itemList.DOC_FILE_TYPE == 'TXT'">{{ txtUrl }}</div> -->

    <!-- ofd shuke-->
    <!-- <shukeOfd v-if="itemList.isTypeShow" :infoItem="infoItem"></shukeOfd> -->
    <shukeOfd :ofdUrl="ofdUrl" v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdUrl && ofdType == 'SUWELL'"
              :style="istype == '1' ? 'height:750px' : 'height:800px'"></shukeOfd>

    <!-- ofd 友虹 -->
    <iframe v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdType == 'SC'" src="/SCOFDReader/v.html" style="width:100%"
            :style="istype == '1' ? 'height:750px' : 'height:800px'" ref="iFrame"></iframe>

    <!--ofd 书生 -->
    <shuShen :ofdUrl="ofdUrl" v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdUrl && ofdType == 'SS'" style="width:100%"
             :style="istype == '1' ? 'height:750px' : 'height:800px'"></shuShen>

    <!--ofd 福昕 -->
    <foxit :ofdUrl="ofdUrl" v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdUrl && ofdType == 'FX'" style="width:100%"
           :style="istype == '1' ? 'height:750px' : 'height:800px'"></foxit>
    <!-- word -->
    <div class="scroll" :style="istype == '1' ? 'height:750px' : 'height:800px'"
      v-if="itemList.DOC_FILE_TYPE == 'DOC' || itemList.DOC_FILE_TYPE == 'DOCX'">
      <div ref="file"></div>
    </div>
    <!-- xls -->
    <div v-if="itemList.DOC_FILE_TYPE == 'XLS' || itemList.DOC_FILE_TYPE == 'XLSX'">

      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane v-for="(item, index) in excelSheet" :key="index" :label="item.name" :name="item.name">
          <div class="table-html-wrap scroll" :style="istype == '1' ? 'height:690px' : 'height: 730px'"
            v-html="item.innerHTML">
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- :page-sizes="[9, 18, 27, 36]" -->
      <el-pagination style="margin-top:10px;float:left" @current-change="changePage" :current-page="currentPage"
        :page-size="dataPerPage" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- mp4 -->
    <div v-if="itemList.DOC_FILE_TYPE == 'MP4' && mp4Url.length > 0" style="width:620px;margin:16% auto 0">
      <video width="620" height="390" controls muted>
        <source :src="mp4Url" type="video/mp4">
        <source src="movie.ogg" type="video/ogg">
      </video>
    </div>

    <!-- mp3 -->
    <div v-if="itemList.DOC_FILE_TYPE == 'MP3' && mp3Url.length > 0" style="width:300px;margin:30% auto 0">
      <audio controls>
        <source :src="mp3Url" type="audio/ogg">
        <source :src="mp3Url" type="audio/mpeg">
      </audio>
    </div>
    <!-- jpg  png -->
    <div v-if='itemList.DOC_FILE_TYPE == "PNG" || itemList.DOC_FILE_TYPE == "JPG" || itemList.DOC_FILE_TYPE == "JPEG"'
      style="position: relative;overflow: hidden;" :style="istype == '1' ? 'height:740px' : 'height: 790px'">
      <previewPicture v-if="imgUrl" :imgUrl="imgUrl"></previewPicture>
    </div>
  </div>
</template>

<script>
import { cutBigPdf, getOfdFile } from "@/api/archive/fileCollection/offlinReception.js";
import pdfDemo from '@/components/componentsPdf/index1.vue'
// 引入docx-preview插件
import { renderAsync } from "docx-preview";
//引入xlsx插件
import * as XLSX from 'xlsx';
// import '@/assets/styles/file.css'//xlsx样式
import previewPicture from '@/components/componentsImg/index.vue'
import axios from "axios";
import { getToken } from "@/utils/auth";
import imgViever from "@/components/ImagePreview/viewer.vue"
import shuShen from "@/components/sushen/index.vue"
import shukeOfd from '@/views/shukeOfd/index'
import foxit from '@/views/fuxinOfd/index'


export default {
  components: { pdfDemo, previewPicture, imgViever, shuShen, shukeOfd, foxit },
  props: ["item", "celldbData", "istype", 'source'],
  watch: {
    item: {
      handler(valNew, valOld) {
        console.log(valNew)
        if (!valNew.DOC_FILE_TYPE.match(/^([A-Z])+$/)) {
          // console.log(valNew.DOC_FILE_TYPE,"valNew.DOC_FILE_TYPE")
          valNew.DOC_FILE_TYPE = valNew.DOC_FILE_TYPE.toUpperCase()

        }
        this.itemList = valNew;
        console.log(this.itemList, "+++++++++")
        this.getdataTap(valNew)
        this.getConfigKey("OfdReadName").then(response => {
          // SC = 友虹 SUWELL = 数科  FX = 福昕 SS = 书生
          this.ofdType = response.msg
        });
      },
      immediate: true,
    }
  },

  data() {
    return {
      itemList: {},
      pdfUrl: "",
      txtUrl: "",
      imgUrl: "",
      mp4Url: "",
      mp3Url: "",
      ofdUrl: "",
      xlsUrl: "",
      excelSheet: [],
      activeName: "",
      // 当前分页
      currentPage: 1,
      // 每页显示数量
      pageSize: 10,
      // 数据总数
      total: 0,
      isUrl: "", //判断显示图片还是pdf
      imgList: [],
      dataPerPage: 10,
      startIndex: 0,
      endIndex: 0,
      tableData: [],
      // ofd类型
      ofdType: '',
    }
  },
  created() {
    // Vue.use(SCOFDReader);
  },
  methods: {
    //===============================start   xls预览==================================
   // tableToHtml 方法用于将 Excel 工作表转换为 HTML 表格字符串，并将其存储在 excelSheet 数组中的对象中。每个对象包含工作表的名称和对应的 HTML 字符串。
    tableToHtml(workbook) {
      var that = this;
      this.excelSheet = [];
      const sheetList = workbook.SheetNames.filter((v) => v.indexOf("数据源") === -1);
      this.activeName = sheetList[0];
      sheetList.forEach((sheet) => {
        const worksheet = workbook.Sheets[sheet];
        if (worksheet) {
          const range = XLSX.utils.decode_range(worksheet["!ref"]);
          range.e.r = Math.min(range.e.r, this.dataPerPage - 1); // Limiting to dataPerPage rows only for preview
          worksheet["!ref"] = XLSX.utils.encode_range(range);
          const innerHTML = XLSX.utils.sheet_to_html(worksheet);
          // console.log(this.generateTableHTML(this.tableDataPage),"skldfjklsdj")
          this.excelSheet.push({
            name: sheet,
            innerHTML: innerHTML,
          });
        } else {
          this.excelSheet.push({
            name: sheet,
            innerHTML: "暂无数据",
          });
        }
      });

      // Calculate start and end indexes for pagination
      that.startIndex = 0;
      that.endIndex = Math.min(that.tableData.length, this.dataPerPage) - 1;
      that.tableDataPage = that.tableData.slice(that.startIndex, that.endIndex + 1);
    },

    //在 readWorkbookFromRemoteFile 方法中，您首先使用 FileReader 读取 Excel 文件的二进制数据。然后使用 XLSX.read 方法将二进制数据解析为工作簿对象 workbook。接下来，您使用 XLSX.utils.sheet_to_json 方法将工作表的数据转换为 JSON 格式，并将其存储在 tableData 数组中。
    readWorkbookFromRemoteFile(file) {
      const that = this;
      let f = file;
      let reader = new FileReader();
      reader.onload = function (e) {
        var data = new Uint8Array(e.target.result);
        var workbook = XLSX.read(data, { type: "array" });

        if (workbook) {
          that.$modal.closeLoading();
        }

        var outdata = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        that.tableData = outdata;
        console.log(that.tableData, "sdkjfklsdjfklj"),
          that.total = outdata.length;
        that.handlePageChange(that.currentPage); // Update the current page data
        that.tableToHtml(workbook);
        console.log(that.total, "skldjfklsdjfklsdjfklsjflksdjf")
      };
      reader.readAsArrayBuffer(f);
    },

    //获取每页加载的数据
    handlePageChange(page) {
      this.excelSheet = [];
      this.currentPage = page;
      this.startIndex = (page - 1) * this.dataPerPage;
      this.endIndex = Math.min(this.startIndex + this.dataPerPage - 1, this.tableData.length - 1);
      this.tableDataPage = this.tableData.slice(this.startIndex, this.endIndex + 1);
    },
    // 定义一个函数，用于生成表格的 HTML
    generateTableHTML(data) {
      let html = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body><table>';

      // 生成表头
      html += '<thead><tr>';
      for (let key in data[0]) {
        html += `<th>${key}</th>`;
      }
      html += '</tr></thead>';

      // 生成表格内容
      html += '<tbody>';
      for (let row of data) {
        html += '<tr>';
        for (let key in row) {
          html += `<td>${row[key]}</td>`;
        }
        html += '</tr>';
      }
      html += '</tbody>';

      html += '</table></body></html>';
      return html;
    },


  //  changePage 方法来更新当前页的数据。然后，您调用了 tableToHtml 方法来生成 HTML 表格字符串，并将它们存储在 excelSheet 数组中的对象中。
    changePage(page) {
      var that = this;
      this.excelSheet = [];
      // this.$modal.loading("正在预览文件，请稍候...")
      this.currentPage = page;
      this.handlePageChange(page);
      console.log(this.excelSheet)

      this.excelSheet.push({
        name: this.activeName,
        innerHTML: this.generateTableHTML(this.tableDataPage),

      });
      // let reader = new FileReader();
      // reader.onload = function (e) {
      //   var data = new Uint8Array(e.target.result);
      //   var workbook = XLSX.read(data, { type: "array" });

      //   if (workbook) {
      //     that.$modal.closeLoading();
      //   }

      //   var outdata = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
      //   that.tableData = outdata;
      //   that.total = outdata.length;
      //   that.handlePageChange(that.currentPage); // Update the current page data
      // //  that.tableToHtml(workbook);
      // };
      // reader.readAsArrayBuffer(this.xlsUrl);

    },
     //===============================end .xls 文件预览===================================================

    // 馆藏预览
    getdataTap(item) {
      var that = this;
      this.pdfUrl = "";
      this.txtUrl = "";
      this.imgUrl = "";
      this.mp4Url = "";
      this.mp3Url = "";
      // console.log(item,"ddd")
      var arr = ['PNG', 'JPG', 'JPEG', 'TXT', 'DOCX', 'XLSX', 'XLS', 'PDF', 'OFD', 'MP3', 'MP4']
      if (!arr.includes(item.DOC_FILE_TYPE)) {
        this.$modal.msgWarning('该文件格式不支持预览')
      }
      if (item.DOC_FILE_TYPE == "DOCX" || item.DOC_FILE_TYPE == "DOC") {

        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'arraybuffer' // 更改responseType类型为 arraybuffer
        }).then(res => {

          this.$nextTick(() => {
            renderAsync(res.data, this.$refs.file).then(x => console.log(
              "docx: finished", x))
          })

        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "PDF") {
        this.isUrl = true
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], { type: 'application/pdf;charset-UTF-8' });
          this.pdfUrl = blob
        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "OFD") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], { type: 'application/ofd;charset-UTF-8' });
          setTimeout(() => {
            var iframeWin = this.$refs.iFrame.contentWindow;

            // iframeWin.onload = function (e) {
            //通过.contentWindow.postMessage(data,"*")向iframe子组件传值
            iframeWin.postMessage({ blob: blob }, "*");
            console.log(iframeWin, "++++")
            // }
          }, 600)
        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "TXT") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new window.Blob([res.data], {
            type: "text/plain",
          })
          this.txtUrl = URL.createObjectURL(blob)

        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "XLSX" || item.DOC_FILE_TYPE == "XLS") {
        this.$modal.loading("加载中")
        async function view() {

          const response = await axios({
            method: 'POST',
            url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
            params: {
              path: item.path
            },
            headers: {
              Authorization: "Bearer " + getToken()
            },
            responseType: 'blob' // 更改responseType类型为 blob
          })
          return response;
        }
        view().then(res => {
          console.log(res.data, "+++++++++++++++++++++++++++++++++11111111111111")
          that.readWorkbookFromRemoteFile(res.data)
        })
        // axios({
        //   method: 'POST',
        //   url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
        //   params: {
        //     path: item.path
        //   },
        //   headers: {
        //     Authorization: "Bearer " + getToken()
        //   },
        //   responseType: 'blob' // 更改responseType类型为 blob
        // }).then(res => {
        //   let file = new File([res.data], 'demo.ofd')
        //   this.readWorkbookFromRemoteFile(file)
        //
        // }).catch(err => {
        //   console.log(err)
        // })
      } else if (item.DOC_FILE_TYPE == "PNG" || item.DOC_FILE_TYPE == "JPG" || item.DOC_FILE_TYPE == "JPEG") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], {
            type: "image/jpeg",
          })
          this.imgUrl = window.URL.createObjectURL(blob)
        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "MP4") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], {
            type: "video/mp4",
          })
          this.$nextTick(res => {
            this.mp4Url = window.URL.createObjectURL(blob)
          })

        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "MP3") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/archive/collection/receive/preview`,
          params: {
            path: item.path
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], {
            type: "audio/mpeg",
          })
          this.$nextTick(res => {
            this.mp3Url = window.URL.createObjectURL(blob)
            var audio = new Audio('mp3/music.mp3');
          })

        }).catch(err => {
          console.log(err)
        })
      }

    }
  }
}
</script>

<style lang="less" scoped>
ul,
li,
p,
div {
  padding: 0;
  margin: 0;
}

/deep/.el-card__body {
  padding: 0;
}

/deep/.el-dialog {
  margin: 25px auto 0 !important;
}


/deep/.el-tabs--border-card>.el-tabs__content {
  padding: 0 !important;
}


.el-col-17 {
  width: 74.83333% !important;
}

.ajinfo {
  position: absolute;
  top: 16px;
  right: 76px;
  color: #fff;
  font-size: 18px;
}

.dataList li {
  font-size: 16px;
  line-height: 50px;
  border-bottom: 1px dashed #cccccc4d;
}

.dataList li p {
  width: 302px;
}

.dataList li label {
  font-weight: bold;
  text-align: right;
  margin-right: 10px;
}

.scroll {
  overflow-y: scroll;
}

.info-scroll {
  overflow-y: scroll;
  height: 900px;
}

.tablist-scroll {
  overflow-y: scroll;
  height: 486px;
}

.box-card1jian {
  height: 526px;
}

.box-card2jian {
  height: 300px;
}

.itemList-scroll {
  overflow-y: scroll;
  height: 256px;

}

.box-cardjian {
  height: 837px;
}





.conterScroll-wj {
  overflow-y: scroll;
  height: 690px;
}

.conterwordScroll {
  overflow-y: scroll;
  height: 800px;
}


.el-dialog {
  margin-bottom: 0 !important;
}

.popup-main .el-tabs__item {
  height: 69px !important;
  line-height: 69px !important;
  font-size: 17px !important;
}

.tablistClass {
  padding: 0px 15px 10px;
}

.tablistClass li {
  height: 40px;
  line-height: 40px;
  font-size: 16px;

}

.chiderAvtia {
  border-bottom: 1px solid #409EFF;
  color: #409EFF;
}



// ofd  显示样式
#divId>div {
  margin: 0 auto;
}


// xls  样式
.table-html-wrap /deep/ table {

  border-collapse: collapse;

}

/deep/.table-html-wrap table {
  border-collapse: collapse;
  vertical-align: top;
  border-style: none;
}

.table-html-wrap /deep/ table td {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}

.table-html-wrap /deep/ table th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}

// -----------------------------------
.headerInfoButton {
  position: absolute;
  top: 16px;
  right: 60px;
}

::v-deep .el-dialog__body {
  padding: 10px 20px 25px !important;
}

.margin_t {
  margin-top: 10px;
}

.text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.flex-row-bowtte {
  display: flex;
  flex-direction: row;
  justify-content: space-between
}

.itemList {
  padding: 10px 15px 10px;
}

.itemList p {
  line-height: 38px;
  display: block;
}
</style>
